import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'index.dart';
import '../../../common/models/chat_message_entity.dart';
import '../../../common/utils/format_util.dart';

/// 聊天页面
class MessageChatPage extends GetView<MessageChatController> {
  const MessageChatPage({super.key});

  // 主视图 - 聊天消息列表 + 输入框
  Widget _buildView() {
    return Column(
      children: [
        // 消息列表区域
        Expanded(
          child: _buildMessageList(),
        ),
        
        // 输入框区域
        _buildInputArea(),
      ],
    );
  }
  
  /// 消息列表
  Widget _buildMessageList() {
    return GestureDetector(
      // 🎯 点击消息列表区域时收起键盘
      onTap: () {
        FocusScope.of(Get.context!).unfocus();
      },
      behavior: HitTestBehavior.translucent,
      child: Obx(() {
        if (controller.messages.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.chat_bubble_outline,
                  size: 64,
                  color: Colors.grey[300],
                ),
                const SizedBox(height: 16),
                Text(
                  '暂无聊天记录',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[400],
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  '发送一条消息开始聊天吧',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[400],
                  ),
                ),
              ],
            ),
          );
        }
        
        return ListView.builder(
          controller: controller.scrollController,
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          // 🔥 企业级优化：添加loading indicator
          itemCount: controller.messages.length + 1, // +1 for loading indicator
          itemBuilder: (context, index) {
            // 🔥 第一项显示loading indicator或"加载更多"提示
            if (index == 0) {
              return Obx(() => _buildLoadingIndicator());
            }
            
            // 其他项显示消息
            final message = controller.messages[index - 1]; // -1 because of loading indicator
            return _buildMessageItem(message);
          },
        );
      }),
    );
  }
  
  /// 🔥 加载指示器（显示在列表顶部）
  Widget _buildLoadingIndicator() {
    if (controller.isLoadingHistory.value) {
      // 正在加载
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 16),
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const SizedBox(
              width: 16,
              height: 16,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF4CAF50)),
              ),
            ),
            const SizedBox(width: 8),
            Text(
              '加载中...',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[400],
              ),
            ),
          ],
        ),
      );
    } else if (controller.hasMoreHistory.value) {
      // 还有更多，显示提示
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 12),
        alignment: Alignment.center,
        child: Text(
          '下拉加载更多历史消息',
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[400],
          ),
        ),
      );
    } else {
      // 没有更多
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 12),
        alignment: Alignment.center,
        child: Text(
          '没有更多消息了',
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[400],
          ),
        ),
      );
    }
  }
  
  /// 单条消息
  Widget _buildMessageItem(ChatMessageEntity message) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Row(
        mainAxisAlignment: message.isMe 
            ? MainAxisAlignment.end 
            : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 对方消息显示头像在左边
          if (!message.isMe) ...[
            _buildAvatar(message.isMe),
            const SizedBox(width: 12),
          ],
          
          // 消息内容
          Flexible(
            child: Column(
              crossAxisAlignment: message.isMe 
                  ? CrossAxisAlignment.end 
                  : CrossAxisAlignment.start,
              children: [
                // 消息气泡
                _buildMessageBubble(message),
                
                // 时间
                Padding(
                  padding: const EdgeInsets.only(top: 4),
                  child: Text(
                    _formatTime(DateTime.fromMillisecondsSinceEpoch(message.timestamp)),
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.grey[400],
                    ),
                  ),
                ),
              ],
            ),
          ),
          
          // 自己的消息显示头像在右边
          if (message.isMe) ...[
            const SizedBox(width: 12),
            _buildAvatar(message.isMe),
          ],
        ],
      ),
    );
  }
  
  /// 头像
  Widget _buildAvatar(bool isMe) {
    if (isMe) {
      // 🎯 显示自己的真实头像
      final myAvatarUrl = controller.userAvatarUrl;
      if (myAvatarUrl.isNotEmpty) {
        return CircleAvatar(
          radius: 20,
          backgroundColor: Colors.grey[200],
          backgroundImage: CachedNetworkImageProvider(myAvatarUrl),
        );
      } else {
        return CircleAvatar(
          radius: 20,
          backgroundColor: Colors.grey[200],
          child: Icon(Icons.person, size: 24, color: Colors.grey[400]),
        );
      }
    } else {
      // 好友头像
      if (controller.friendAvatar.isNotEmpty) {
        return CircleAvatar(
          radius: 20,
          backgroundColor: Colors.grey[200],
          backgroundImage: CachedNetworkImageProvider(controller.friendAvatar),
        );
      } else {
        return CircleAvatar(
          radius: 20,
          backgroundColor: Colors.grey[200],
          child: Icon(Icons.person, size: 24, color: Colors.grey[400]),
        );
      }
    }
  }
  
  /// 消息气泡
  Widget _buildMessageBubble(ChatMessageEntity message) {
    return Container(
      constraints: const BoxConstraints(maxWidth: 260),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      decoration: BoxDecoration(
        color: message.isMe 
            ? const Color(0xFF4CAF50)  // 自己的消息：绿色
            : Colors.white,             // 对方的消息：白色
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Text(
        message.content,
        style: TextStyle(
          fontSize: 15,
          color: message.isMe ? Colors.white : const Color(0xFF333333),
          height: 1.4,
        ),
      ),
    );
  }
  
  /// 输入框区域
  Widget _buildInputArea() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(
            color: Colors.grey[200]!,
            width: 1,
          ),
        ),
      ),
      child: Row(
        children: [
          // 输入框
          Expanded(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                color: const Color(0xFFF5F5F5),
                borderRadius: BorderRadius.circular(20),
              ),
              child: TextField(
                controller: controller.textController,
                decoration: const InputDecoration(
                  hintText: '输入消息...',
                  hintStyle: TextStyle(
                    fontSize: 14,
                    color: Color(0xFF999999),
                  ),
                  border: InputBorder.none,
                  isDense: true,
                  contentPadding: EdgeInsets.zero,
                ),
                style: const TextStyle(
                  fontSize: 15,
                  color: Color(0xFF333333),
                ),
                maxLines: 4,
                minLines: 1,
                textInputAction: TextInputAction.send,
                onSubmitted: (_) => controller.sendMessage(),
              ),
            ),
          ),
          
          const SizedBox(width: 12),
          
          // 发送按钮
          GestureDetector(
            onTap: controller.sendMessage,
            child: Container(
              width: 40,
              height: 40,
              decoration: const BoxDecoration(
                color: Color(0xFF4CAF50),
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.send,
                color: Colors.white,
                size: 20,
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  /// 格式化时间（使用 FormatUtil 工具类）
  String _formatTime(DateTime time) {
    return FormatUtil.formatChatTime(time);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MessageChatController>(
      init: MessageChatController(),
      id: "message_chat",
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFF5F5F5),
          appBar: AppBar(
            leading: IconButton(
              icon: const Icon(
                Icons.arrow_back_ios,
                color: Colors.black87,
                size: 20,
              ),
              onPressed: () => Get.back(),
            ),
            // ✅ 显示好友名称和头像作为标题
            title: Row(
              children: [
                // 好友头像
                if (controller.friendAvatar.isNotEmpty)
                  CircleAvatar(
                    radius: 18,
                    backgroundColor: Colors.grey[200],
                    backgroundImage: CachedNetworkImageProvider(controller.friendAvatar),
                  )
                else
                  CircleAvatar(
                    radius: 18,
                    backgroundColor: Colors.grey[200],
                    child: Icon(Icons.person, size: 20, color: Colors.grey[400]),
                  ),
                const SizedBox(width: 12),
                // 好友名称
                Text(
                  controller.friendName,
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF333333),
                  ),
                ),
              ],
            ),
            backgroundColor: Colors.white,
            elevation: 0,
            systemOverlayStyle: const SystemUiOverlayStyle(
              statusBarColor: Colors.transparent,
              statusBarIconBrightness: Brightness.dark,
            ),
          ),
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }
}
